from loguru import logger

from com.arcfox.school.processor.base_processor import BaseProcessor
from bs4 import BeautifulSoup
from com.arcfox.middleware import async_mysql_middleware as db


class EolSchoolTitleProcessor(BaseProcessor):
    def __init__(self):
        self.title_mapping = {
            "985": 1,
            "211": 2,
            "双一流": 3,
            "中央部委直属": 4,
            "教育部直属": 5,
            "国家示范性高职": 6,
            "国家骨干高职": 7,
        }

    async def parse_and_save_data(self, task, html):
        logger.info(task)
        university_title = task['title']
        soup = BeautifulSoup(html, "lxml")
        class_name = self.get_class_name(task)
        if not class_name:
            return
        div_tag = soup.find("div", {"class": class_name})
        a_tags = div_tag.find_all("a")
        for a_tag in a_tags:
            university_name = ''
            if task['title'] == '国家骨干高职':
                if a_tag.has_attr('target') and a_tag.attrs['target'] == "_blank":
                    university_name = a_tag.text
            else:
                if "provinceline" not in a_tag.attrs['href']:
                    university_name = a_tag.text
            if university_name:
                university_uid = self.generate_school_uid(university_name)
                title_type = self.title_mapping[university_title]
                data = {
                    "university_name": university_name,
                    "university_uid": university_uid,
                    "university_title": university_title,
                    "title_type": title_type
                }
                mapping = db.MysqlMapping("tb_university_title")
                old_data = await mapping.query({"university_uid": university_uid, "title_type": title_type}, ["id"])
                if old_data:
                    logger.info("数据已存在!")
                else:
                    await mapping.insert(data)

    def get_class_name(self, task):
        if task['title'] == "985":
            return "tablebox"
        elif task['title'] == "211":
            return "con-table"
        elif task['title'] == "双一流":
            return None
        elif task['title'] == "中央部委直属":
            return "tablebox"
        elif task['title'] == "教育部直属":
            return "con-table"
        elif task['title'] == "国家示范性高职":
            return "con-table"
        elif task['title'] == "国家骨干高职":
            return "con-table"
        else:
            return None